<template>
    <table style="width: 100%">
      <thead></thead>
      <tbody>
        <tr>
          <td>
            <div style="margin-left: 15%;">
              <h2>路线信息</h2>
              <p>起点：{{ address.startaddr }}</p> 
              <p>终点：{{ address.endaddr }}</p>
              <p>运输状况: {{address.abnormalalarms}} </p>
              <p> <button>呼叫负责人</button><button>呼叫司机</button> </p>
              <p>总距离: {{6 }} 米</p>
              <p>预计行驶时间: {{ getEstimatedTime() }} 分钟</p>
              <!-- <p>当前位置:{{ address.endaddr }}</p>
              <p>当前坐标:{{ address.endaddr }}</p> -->
              <p> <button>一键呼叫紧急救援</button><button>一键呼叫急救120</button> </p>
            </div>
          </td>
          <td style="width: 70%">
            <div id="map" style="width: 100%; height: 500px"></div>
          </td>
        </tr>
      </tbody>
    </table>
  
  
    <div>
      <p>Distance: {{ distance }} km</p>
    </div>
  </template>
  
  <script setup lang="ts">
  import { reactive, ref, onMounted, onUnmounted } from 'vue';
  import { useRoute } from 'vue-router';
  const route = useRoute();
  // 地址信息
  const address = ref({
    startaddr: route.query.startingCounty || '',
    endaddr: route.query.endCounty || '',
    abnormalalarms: route.query.abnormalalarms || '',
  });
  
  const lat1 = ref<number | null>(null);
  const lon1 = ref<number | null>(null);
  const lat2 = ref<number | null>(null);
  const lon2 = ref<number | null>(null);
  const distance = ref<number | null>(null);
   
  const calculateDistance = () => {
    if (
      lat1.value === null ||
      lon1.value === null ||
      lat2.value === null ||
      lon2.value === null
    ) {
      alert("Please enter all coordinates.");
      return;
    }
   
    const R = 6371; // 地球半径，单位：千米
    const rad = (d: number): number => d * Math.PI / 180; // 角度转弧度
   
    const dLat = rad(lat2.value! - lat1.value!);
    const dLon = rad(lon2.value! - lon1.value!);
    const a =
      Math.sin(dLat / 2) ** 2 +
      Math.cos(rad(lat1.value!)) * Math.cos(rad(lat2.value!)) *
        Math.sin(dLon / 2) ** 2;
    const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
   
    distance.value = R * c; // 距离，单位：千米
  };
  
  
  
  // 地图信息
  const mapInfo = reactive({
    map: null as BMap.Map | null,
    drivingRoute: null as BMap.DrivingRouteResult | null,
    startPoint: null as BMap.Point | null,
    endPoint: null as BMap.Point | null,
    currentPositionMarker: null as BMap.Marker | null,
    trackingInterval: null as number | null,
  });
  
  // 加载百度地图API
  const loadMapApi = () => {
    const script = document.createElement('script');
    script.src = 'https://api.map.baidu.com/api?v=3.0&ak=bXXLDppFNCOhnEZFFmWsJmb7QVpb6Byx'; // 替换为您的API密钥
    script.onload = initMap;
    document.head.appendChild(script);
  };
  
  // 初始化地图
  const initMap = async () => {
    mapInfo.map = new BMap.Map('map');
    mapInfo.map.centerAndZoom(new BMap.Point(116.404, 39.915), 11);
    mapInfo.map.enableScrollWheelZoom(true);
  
    await convertAddressToLatLng(address.value.startaddr).then(startPoint => {
      mapInfo.startPoint = startPoint;
      return convertAddressToLatLng(address.value.endaddr);
    }).then(endPoint => {
      mapInfo.endPoint = endPoint;
      planRoute();
    }).catch(error => {
      console.error('地址转换失败', error);
    });
  };
  
  // 地址转换为经纬度
  const convertAddressToLatLng = (address: string): Promise<BMap.Point | undefined> => {
    return new Promise((resolve, reject) => {
      const myGeo = new BMap.Geocoder();
      myGeo.getPoint(address, (point) => {
        if (point) {
          resolve(point);
        } else {
          reject(new Error('地址转换失败'));
        }
      }, '北京市');
    });
  };
  
  // 规划路线
  const planRoute = () => {
    if (mapInfo.startPoint && mapInfo.endPoint) {
      const driving = new BMap.DrivingRoute(mapInfo.map!, {
        renderOptions: { map: mapInfo.map!, autoViewport: true }
      });
      driving.search(mapInfo.startPoint, mapInfo.endPoint, (result) => {
        if (result && result.getNumRoutes() > 0) {
          mapInfo.drivingRoute = result.getRoutes()[0];
          mapInfo.map!.setViewport(mapInfo.drivingRoute.getBoundingClientRect());
  
          const routePath = mapInfo.drivingRoute.getPath();
          const polyline = new BMap.Polyline(routePath, {
            strokeColor: 'blue',
            strokeWeight: 6,
            strokeOpacity: 0.8
          });
          mapInfo.map!.addOverlay(polyline);
  
          addMarkerWithInfoWindow(mapInfo.startPoint, '起点：' + address.value.startaddr);
          addMarkerWithInfoWindow(mapInfo.endPoint, '终点：' + address.value.endaddr);
        } else {
          console.error('路线规划失败');
        }
      });
    }
  };
  
  // 添加标记和信息窗口
  const addMarkerWithInfoWindow = (point: BMap.Point, title: string) => {
    const marker = new BMap.Marker(point);
    mapInfo.map!.addOverlay(marker);
    const infoWindow = new BMap.InfoWindow(title);
    marker.addEventListener('click', () => {
      mapInfo.map!.openInfoWindow(infoWindow, point);
    });
  };
  
  // 清理函数
  const cleanup = () => {
    if (mapInfo.trackingInterval) clearInterval(mapInfo.trackingInterval);
    if (mapInfo.currentPositionMarker) {
      mapInfo.map!.removeOverlay(mapInfo.currentPositionMarker);
    }
  };
  
  // 生命周期钩子
  onMounted(() => {
    loadMapApi();
  });
  
  onUnmounted(() => {
    cleanup();
  });
  
  // 获取总距离和预计时间
  const getTotalDistance = () => {
    return mapInfo.drivingRoute ? mapInfo.drivingRoute.getDistance() : 0;
  };
  
  const getEstimatedTime = () => {
    return mapInfo.drivingRoute ? Math.round(mapInfo.drivingRoute.getDuration() / 60) : 0;
  };
  </script>
  
  <style scoped>
  #map {
    width: 100%;
    height: 500px;
  }
  </style>